package com.wlz.directbuffer;

import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;

/**
 *  直接内存 与 堆内存的区别
 * @author wlz
 * @date 2022-07-10  12:11 下午
 */
@Slf4j
public class DirectMemoryTest {

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            heapAccess();;
            directAccess();
        }
        
        log.info(" ======================== ");

        for (int i = 0; i < 10; i++) {
            heapAllocate();
            directAllocate();
        }
    }

    public static void heapAccess() {
        long startTime = System.currentTimeMillis();
        // 分配堆内存
        ByteBuffer buffer = ByteBuffer.allocate(1000);
        for (int i = 0; i < 100000; i++) {
            for (int j = 0; j < 200; j++) {
                buffer.putInt(j);
            }
            buffer.flip();
            for (int j = 0; j < 200; j++) {
                buffer.getInt();
            }
            buffer.clear();
        }
        long endTime = System.currentTimeMillis();
        log.info("堆内存访问:  {} ms", endTime - startTime);
    }


    public static void directAccess() {
        long startTime = System.currentTimeMillis();
        // 分配直接内存
        ByteBuffer buffer = ByteBuffer.allocateDirect(1000);
        for (int i = 0; i < 100000; i++) {
            for (int j = 0; j < 200; j++) {
                buffer.putInt(j);
            }
            buffer.flip();
            for (int j = 0; j < 200; j++) {
                buffer.getInt();
            }
            buffer.clear();
        }
        log.info("直接内存访问: {} ms", System.currentTimeMillis() - startTime);
    }

    public static void heapAllocate() {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            ByteBuffer.allocate(100);
        }
        log.info(" 堆内存申请； {}  ms", System.currentTimeMillis()- startTime);
    }

    public static void directAllocate() {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            ByteBuffer.allocateDirect(100);
        }
        log.info("直接内存申请: {}  ms", System.currentTimeMillis() - startTime);
    }

}
